﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Diagnostics;
using System.Xml.Linq;
using Microsoft.Phone.Shell;

namespace ByrForum
{
    public partial class ArticleList : PhoneApplicationPage
    {
        bool if_loaded = false;
        ApplicationBarIconButton BarButtonForward;
        ApplicationBarIconButton BarButtonBackward;
        public int total_page = 1;
        public int current_page = 1;
        string boardname = "";
        List<ArticleInfo> listArticle = new List<ArticleInfo>();
        public ArticleList()
        {
            InitializeComponent();
            BarButtonForward = this.ApplicationBar.Buttons[2] as ApplicationBarIconButton;
            BarButtonBackward = this.ApplicationBar.Buttons[0] as ApplicationBarIconButton;
            BarButtonForward.IsEnabled = false;
            BarButtonBackward.IsEnabled = false;
        }

        private void OnListItemSelected(object sender, SelectionChangedEventArgs e)
        {

        }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (!if_loaded)
            {
                IDictionary<string, string> queryString = this.NavigationContext.QueryString;
                
                try
                {
                    queryString.TryGetValue("boardname", out boardname);
                }
                catch
                {
                    base.OnNavigatedTo(e);
                    return;
                }

                String myRequestUrl = ByrApi.apiUrl + "/board/" + boardname + ByrApi.Encode + ByrApi.appkey;
                HttpUtil.HttpGet(myRequestUrl, HttpWebRequset_Callback);
                Debug.WriteLine(myRequestUrl);
                progressBarWait.Visibility = Visibility.Visible;
                listArticle.Clear();
                listbox.Items.Clear();
                if_loaded = true;
            }
        }
        private void HttpWebRequset_Callback(IAsyncResult asynchronousResult)
        {

            try
            {
                string result = HttpUtil.ReadToEnd(asynchronousResult);
                DebugInfo.writeXml(result);
                XDocument doc = XDocument.Parse(result);
                Debug.WriteLine(((XElement)doc.FirstNode).Name);

                foreach (XElement item in doc.Descendants("pagination").Nodes())
                {
                    switch (item.Name.ToString())
                    { 
                    
                        case "page_all_count":
                            total_page = Convert.ToInt16( item.Value);
                            break;
                        case "page_current_count":
                            current_page =Convert.ToInt16( item.Value.ToString());
                            if (current_page != 1)
                            {
                                BarButtonBackward.IsEnabled = true;
                            }
                            if (current_page == total_page)
                            {
                                BarButtonForward.IsEnabled = false;
                            }
                            else
                                BarButtonForward.IsEnabled = true;
                            break;
                        default:
                            break;
                    }
                }

                foreach (XElement item in doc.Descendants("board").Nodes())
                {
                    Debug.WriteLine(item.Name);
                    if (item.Name == "description")
                    {
                        string value = item.Value;
                        this.Dispatcher.BeginInvoke(
                            () => {
                                this.PageTitle.Text = value;
                            }
                            );
                    }
                }

                foreach (XElement item in doc.Descendants("article").Nodes())
                {
                    string group_id = "", title = "", user_id = "", post_time = "";
                    if (item.Name == "item")
                    {
                        
                        foreach(XElement child_item in item.Elements())
                        {
                            switch (child_item.Name.ToString())
                            { 
                                case "group_id":
                                    group_id = child_item.Value;
                                    break;
                                case "title":
                                    title = child_item.Value;
                                    Debug.WriteLine(title);
                                    break;
                                case "post_time":
                                    post_time = child_item.Value;
                                    break;
                                default :
                                    break;
                            }
                            if (child_item.Name == "user")
                            {
                                foreach (XElement user_item in child_item.Elements())
                                {
                                    if (user_item.Name == "id")
                                        user_id = user_item.Value;

                                }
                            }
                        }

                        this.Dispatcher.BeginInvoke(
                        () =>
                        {
                            listbox.Items.Add(new ArticleInfo(boardname, group_id, title, user_id));
                        }
                        );
                        listArticle.Add(new ArticleInfo(boardname, group_id, title, user_id));
                    }
                    
                    
                    
                }

                this.Dispatcher.BeginInvoke(
                    () => {
                        this.progressBarWait.Visibility = Visibility.Collapsed;
                    }
                    );
            }
            catch(Exception e)
            {
                Debug.WriteLine("get callback failed");
                Debug.WriteLine(e.Message);
                this.Dispatcher.BeginInvoke(
                    () =>
                    {
                        this.progressBarWait.Visibility = Visibility.Collapsed;
                    }
                    );
            }
        }

        private void listbox_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (!if_loaded || (((ListBox)sender).SelectedIndex == -1))
                return;
            this.NavigationService.Navigate(new Uri("/TopTen.xaml?board=" + listArticle[((ListBox)sender).SelectedIndex].Board
               + "&group_id=" + listArticle[((ListBox)sender).SelectedIndex].Group_id
               + "&title=" + listArticle[((ListBox)sender).SelectedIndex].Title, UriKind.Relative));

        }

        private void ApplicationBarIconButtonForward_Click(object sender, EventArgs e)
        {
            String myRequestUrl = ByrApi.apiUrl + "/board/" +boardname+ ByrApi.Encode + ByrApi.appkey + "page=" + (++current_page).ToString(); ;
            listbox.Items.Clear();
            listArticle.Clear();
            HttpUtil.HttpGet(myRequestUrl, HttpWebRequset_Callback);
            Debug.WriteLine(myRequestUrl);
            progressBarWait.Visibility = Visibility.Visible;
            if (current_page == total_page)
            {
                BarButtonForward.IsEnabled = false;
            }
            if (current_page != 1)
            {
                BarButtonBackward.IsEnabled = true;
            }
        }

        private void ApplicationBarIconButtonBack_Click(object sender, EventArgs e)
        {
            String myRequestUrl = ByrApi.apiUrl + "/board/" + boardname + ByrApi.Encode + ByrApi.appkey + "page=" + (--current_page).ToString(); ;
            listbox.Items.Clear();
            listArticle.Clear();
            Debug.WriteLine(myRequestUrl);
            HttpUtil.HttpGet(myRequestUrl, HttpWebRequset_Callback);
            progressBarWait.Visibility = Visibility.Visible;
            if (current_page != total_page)
            {
                BarButtonForward.IsEnabled = true;
            }
            if (current_page == 1)
            {
                BarButtonBackward.IsEnabled = false;
            }
        }

        private void ApplicationBarIconButtonAdd_Click(object sender, EventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/AddNewPost.xaml?boardname="+boardname+"&id="+"",UriKind.Relative));
        }
    }
}